package net.caixiaomi.info.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.igexin.sdk.GTIntentService;
import com.igexin.sdk.message.GTCmdMessage;
import com.igexin.sdk.message.GTNotificationMessage;
import com.igexin.sdk.message.GTTransmitMessage;

import net.caixiaomi.info.Lottery.ui.BallLotteryMainActivity;
import net.caixiaomi.info.MainActivity;
import net.caixiaomi.info.R;
import net.caixiaomi.info.WebViewActivity;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.ui.details.ArticleDetailActivity;
import net.caixiaomi.info.ui.football.PlayFootballActivity;
import net.caixiaomi.info.ui.football.detail.MatchDetailActivity;
import net.caixiaomi.info.ui.login.LoginActivity;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.ToastUtil;

import java.util.Random;

/**
 * 继承 GTIntentService 接收来自个推的消息, 所有消息在线程中回调, 如果注册了该服务, 则务必要在 AndroidManifest中声明, 否则无法接受消息<br>
 * onReceiveMessageData 处理透传消息<br>
 * onReceiveClientId 接收 cid <br>
 * onReceiveOnlineState cid 离线上线通知 <br>
 * onReceiveCommandResult 各种事件处理回执 <br>
 */
public class CXMIntentService extends GTIntentService {

    private static final String TAG = "CXMIntentService";

    /**
     * 为了观察透传数据变化.
     */
    private static int cnt;

    public CXMIntentService() {

    }

    @Override
    public void onReceiveServicePid(Context context, int pid) {
        Log.d(TAG, "onReceiveServicePid -> " + pid);
    }

    @Override
    public void onReceiveMessageData(Context context, GTTransmitMessage msg) {
        String appid = msg.getAppid();
        String taskid = msg.getTaskId();
        String messageid = msg.getMessageId();
        byte[] payload = msg.getPayload();
        String pkg = msg.getPkgName();
        String cid = msg.getClientId();

        // 第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
//        boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, 90001);
//        Log.d(TAG, "call sendFeedbackMessage = " + (result ? "success" : "failed"));

        Log.d(TAG, "onReceiveMessageData -> " + "appid = " + appid + "\ntaskid = " + taskid + "\nmessageid = " + messageid + "\npkg = " + pkg
                + "\ncid = " + cid);

        if (payload == null) {
            Log.e(TAG, "receiver payload = null");
        } else {
            String data = new String(payload);
            Log.d(TAG, "receiver payload = " + data);
            sendNotification(data);
        }

        Log.d(TAG, "----------------------------------------------------------------------------------------------");
    }

    @Override
    public void onReceiveClientId(Context context, String clientid) {
        CommonApp.STORE.set(Constants.KEY_PUSH_CLIENT_ID, clientid);
        Log.e(TAG, "onReceiveClientId -> " + "clientid = " + clientid);

//        sendMessage(clientid, 1);
    }

    @Override
    public void onReceiveOnlineState(Context context, boolean online) {
        Log.d(TAG, "onReceiveOnlineState -> " + (online ? "online" : "offline"));
    }

    @Override
    public void onReceiveCommandResult(Context context, GTCmdMessage cmdMessage) {
        Log.d(TAG, "onReceiveCommandResult -> " + cmdMessage);

        int action = cmdMessage.getAction();

//        if (action == PushConsts.SET_TAG_RESULT) {
//            setTagResult((SetTagCmdMessage) cmdMessage);
//        } else if(action == PushConsts.BIND_ALIAS_RESULT) {
//            bindAliasResult((BindAliasCmdMessage) cmdMessage);
//        } else if (action == PushConsts.UNBIND_ALIAS_RESULT) {
//            unbindAliasResult((UnBindAliasCmdMessage) cmdMessage);
//        } else if ((action == PushConsts.THIRDPART_FEEDBACK)) {
//            feedbackResult((FeedbackCmdMessage) cmdMessage);
//        }
    }

    @Override
    public void onNotificationMessageArrived(Context context, GTNotificationMessage message) {


        Log.d(TAG, "onNotificationMessageArrived -> " + "appid = " + message.getAppid() + "\ntaskid = " + message.getTaskId() + "\nmessageid = "
                + message.getMessageId() + "\npkg = " + message.getPkgName() + "\ncid = " + message.getClientId() + "\ntitle = "
                + message.getTitle() + "\ncontent = " + message.getContent());
    }

    @Override
    public void onNotificationMessageClicked(Context context, GTNotificationMessage message) {
        Log.d(TAG, "onNotificationMessageClicked -> " + "appid = " + message.getAppid() + "\ntaskid = " + message.getTaskId() + "\nmessageid = "
                + message.getMessageId() + "\npkg = " + message.getPkgName() + "\ncid = " + message.getClientId() + "\ntitle = "
                + message.getTitle() + "\ncontent = " + message.getContent());
    }

//    private void setTagResult(SetTagCmdMessage setTagCmdMsg) {
//        String sn = setTagCmdMsg.getSn();
//        String code = setTagCmdMsg.getCode();
//
//        int text = R.string.add_tag_unknown_exception;
//        switch (Integer.valueOf(code)) {
//            case PushConsts.SETTAG_SUCCESS:
//                text = R.string.add_tag_success;
//                break;
//
//            case PushConsts.SETTAG_ERROR_COUNT:
//                text = R.string.add_tag_error_count;
//                break;
//
//            case PushConsts.SETTAG_ERROR_FREQUENCY:
//                text = R.string.add_tag_error_frequency;
//                break;
//
//            case PushConsts.SETTAG_ERROR_REPEAT:
//                text = R.string.add_tag_error_repeat;
//                break;
//
//            case PushConsts.SETTAG_ERROR_UNBIND:
//                text = R.string.add_tag_error_unbind;
//                break;
//
//            case PushConsts.SETTAG_ERROR_EXCEPTION:
//                text = R.string.add_tag_unknown_exception;
//                break;
//
//            case PushConsts.SETTAG_ERROR_NULL:
//                text = R.string.add_tag_error_null;
//                break;
//
//            case PushConsts.SETTAG_NOTONLINE:
//                text = R.string.add_tag_error_not_online;
//                break;
//
//            case PushConsts.SETTAG_IN_BLACKLIST:
//                text = R.string.add_tag_error_black_list;
//                break;
//
//            case PushConsts.SETTAG_NUM_EXCEED:
//                text = R.string.add_tag_error_exceed;
//                break;
//
//            default:
//                break;
//        }
//
//        Log.d(TAG, "settag result sn = " + sn + ", code = " + code + ", text = " + getResources().getString(text));
//    }
//
//    private void bindAliasResult(BindAliasCmdMessage bindAliasCmdMessage) {
//        String sn = bindAliasCmdMessage.getSn();
//        String code = bindAliasCmdMessage.getCode();
//
//        int text = R.string.bind_alias_unknown_exception;
//        switch (Integer.valueOf(code)) {
//            case PushConsts.BIND_ALIAS_SUCCESS:
//                text = R.string.bind_alias_success;
//                break;
//            case PushConsts.ALIAS_ERROR_FREQUENCY:
//                text = R.string.bind_alias_error_frequency;
//                break;
//            case PushConsts.ALIAS_OPERATE_PARAM_ERROR:
//                text = R.string.bind_alias_error_param_error;
//                break;
//            case PushConsts.ALIAS_REQUEST_FILTER:
//                text = R.string.bind_alias_error_request_filter;
//                break;
//            case PushConsts.ALIAS_OPERATE_ALIAS_FAILED:
//                text = R.string.bind_alias_unknown_exception;
//                break;
//            case PushConsts.ALIAS_CID_LOST:
//                text = R.string.bind_alias_error_cid_lost;
//                break;
//            case PushConsts.ALIAS_CONNECT_LOST:
//                text = R.string.bind_alias_error_connect_lost;
//                break;
//            case PushConsts.ALIAS_INVALID:
//                text = R.string.bind_alias_error_alias_invalid;
//                break;
//            case PushConsts.ALIAS_SN_INVALID:
//                text = R.string.bind_alias_error_sn_invalid;
//                break;
//            default:
//                break;
//
//        }
//
//        Log.d(TAG, "bindAlias result sn = " + sn + ", code = " + code + ", text = " + getResources().getString(text));
//
//    }

    //    private void unbindAliasResult(UnBindAliasCmdMessage unBindAliasCmdMessage) {
//        String sn = unBindAliasCmdMessage.getSn();
//        String code = unBindAliasCmdMessage.getCode();
//
//        int text = R.string.unbind_alias_unknown_exception;
//        switch (Integer.valueOf(code)) {
//            case PushConsts.UNBIND_ALIAS_SUCCESS:
//                text = R.string.unbind_alias_success;
//                break;
//            case PushConsts.ALIAS_ERROR_FREQUENCY:
//                text = R.string.unbind_alias_error_frequency;
//                break;
//            case PushConsts.ALIAS_OPERATE_PARAM_ERROR:
//                text = R.string.unbind_alias_error_param_error;
//                break;
//            case PushConsts.ALIAS_REQUEST_FILTER:
//                text = R.string.unbind_alias_error_request_filter;
//                break;
//            case PushConsts.ALIAS_OPERATE_ALIAS_FAILED:
//                text = R.string.unbind_alias_unknown_exception;
//                break;
//            case PushConsts.ALIAS_CID_LOST:
//                text = R.string.unbind_alias_error_cid_lost;
//                break;
//            case PushConsts.ALIAS_CONNECT_LOST:
//                text = R.string.unbind_alias_error_connect_lost;
//                break;
//            case PushConsts.ALIAS_INVALID:
//                text = R.string.unbind_alias_error_alias_invalid;
//                break;
//            case PushConsts.ALIAS_SN_INVALID:
//                text = R.string.unbind_alias_error_sn_invalid;
//                break;
//            default:
//                break;
//
//        }
//
//        Log.d(TAG, "unbindAlias result sn = " + sn + ", code = " + code + ", text = " + getResources().getString(text));
//
//    }
//
//
//    private void feedbackResult(FeedbackCmdMessage feedbackCmdMsg) {
//        String appid = feedbackCmdMsg.getAppid();
//        String taskid = feedbackCmdMsg.getTaskId();
//        String actionid = feedbackCmdMsg.getActionId();
//        String result = feedbackCmdMsg.getResult();
//        long timestamp = feedbackCmdMsg.getTimeStamp();
//        String cid = feedbackCmdMsg.getClientId();
//
//        Log.d(TAG, "onReceiveCommandResult -> " + "appid = " + appid + "\ntaskid = " + taskid + "\nactionid = " + actionid + "\nresult = " + result
//                + "\ncid = " + cid + "\ntimestamp = " + timestamp);
//    }
//
//    private void sendMessage(String data, int what) {
//        Message msg = Message.obtain();
//        msg.what = what;
//        msg.obj = data;
//        DemoApplication.sendMessage(msg);
//    }
    private NotificationManager mNotificationManager;

    static int DEFAULT_NID = 1000;

    private void sendNotification(String message) {
        mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

        try {
            JSONObject data = JSON.parseObject(message);
            Intent intent = new Intent(this, MainActivity.class);
            String strType = data.getString("type");
            String id = data.getString("id");
            String subid = data.getString("subid");
            String title = data.getString("title");
            String content = data.getString("content");

            if(!TextUtils.isEmpty(strType)){
                int type = Integer.valueOf(strType);
                if (type == 1) {//
                    intent.setClass(this, WebViewActivity.class);
                    intent.putExtra("url", id);
                } else if (type == 3) {
                    if(TextUtils.equals(id,"1")){
                        intent.setClass(this, PlayFootballActivity.class);
                        intent.putExtra("playType", subid);
                    }else if(TextUtils.equals(id,"2")){
                        intent.setClass(this, BallLotteryMainActivity.class);
                        intent.putExtra("playType", subid);
                    }else{
//                        ToastUtil.s("敬请期待");
                    }
//                    intent.setClass(this, PlayFootballActivity.class);
//                    intent.putExtra("playType", subid);
                } else if (type == 4) {
                    intent.setClass(this, MatchDetailActivity.class);
                    intent.putExtra("data", id);
                } else if (type == 8) {
                    intent.setClass(this, ArticleDetailActivity.class);
                    intent.putExtra("data", id);
                } else if (type == 5) {
                    intent.setClass(this, LoginActivity.class);
                }
            }


            Notification n = null;
            int nid = DEFAULT_NID++;

            Drawable d = getResources().getDrawable(R.drawable.ic_launcher);
            Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
            Random random = new Random();

            PendingIntent pi = PendingIntent.getActivity(this, random.nextInt(100), intent, PendingIntent.FLAG_UPDATE_CURRENT);
            Notification.Builder mBuilder = new Notification.Builder(this)
                    .setLargeIcon(bitmap)
                    .setSmallIcon(R.drawable.ic_notification_small)
                    .setContentTitle(title)
                    .setContentText(content)
                    .setAutoCancel(true);


            if (Build.VERSION.SDK_INT >= 16) {
                mBuilder.setStyle(new Notification.BigTextStyle().bigText(content));
            }
            mBuilder.setContentIntent(pi);

            if (Build.VERSION.SDK_INT >= 16) {
                n = mBuilder.build();
            } else {
                n = mBuilder.getNotification();
            }

            AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            int curMode = audioManager.getRingerMode();

            if (curMode == AudioManager.RINGER_MODE_NORMAL) {
                n.defaults |= Notification.DEFAULT_SOUND;
            } else if (curMode == AudioManager.RINGER_MODE_VIBRATE) {
                n.defaults |= Notification.DEFAULT_VIBRATE;
            } else {
                n.defaults |= Notification.DEFAULT_LIGHTS;
            }

            mNotificationManager.notify(nid, n);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
